import JSEncrypt from "jsencrypt";
export const addScript = (
  path: string,
  diffStr: string,
  callback: () => void
) => {
  const head = document.getElementsByTagName("head")[0];
  const scripts = head.getElementsByTagName("script");
  const deleteScripts: any[] = [];
  for (let i = 0; i < scripts.length; i++) {
    const thisScript = scripts[i];
    const src = thisScript.getAttribute("src");
    if ((diffStr && src && src?.indexOf(diffStr) > -1) || src == path) {
      deleteScripts.push(thisScript);
    }
  }
  deleteScripts.forEach((v) => {
    v.parentNode.removeChild(v);
  });
  window.initAliyunCaptcha = null;
  const js: any = document.createElement("script");
  js.setAttribute("src", path);
  js.setAttribute("type", "text/javascript");
  js.onload = js.onreadystatechange = function () {
    if (
      !this.readyState ||
      this.readyState === "loaded" ||
      this.readyState === "complete"
    ) {
      if (callback && typeof callback === "function") {
        callback();
      }
      js.onload = js.onreadystatechange = null;
    }
  };
  head.appendChild(js);
};

/**
 *
 * @param param 需要加密的字段值
 * @param publicKey 公钥
 * @returns 返回加密值
 */
export const encryptParma = (param: string, publicKey: string): string => {
  const Encryptor = new JSEncrypt();
  Encryptor.setPublicKey(publicKey);
  return Encryptor.encrypt(param) as string;
};
